<?php
/**
 * 菜单服务
 * @Auther 聂哥<376927050@qq.com>
 * @Date: 2022-10-12 11:27:48
*/
namespace app\admin\service;

use app\admin\model\system\SystemRole;
use app\admin\model\system\SystemMenu;
use think\facade\Cache;
use think\facade\Session;

class MenuService
{
    /**
     * 获取指定角色下的所有菜单ids
     * @MethodAuthor: 聂哥
     * @Date: 2022-10-28 15:32:09
     */
    public static function getSystemMenuIdsByRole(array $ids)
    {
        $roles = SystemRole::whereIn('id',$ids)->select();
        if( $roles == null ){
            return [];
        }
        $allAuths = array_column($roles->toArray(),'auth');
        $menu_ids = implode(',',$allAuths);
        return array_unique(explode(',',$menu_ids));
    }
    
    /**
     * 通过角色ids获取菜单列表
     * @MethodAuthor: 聂哥
     * @Date: 2022-10-28 15:32:09
     */
    public static function getSystemMenuListByRole(array $ids = [1],$moduleName)
    {
        $map['module'] = $moduleName ?? 'system';
        $map['status'] = SystemMenu::NORMAL_STATE;
        if( in_array(SystemRole::SUPER_ADMIN,$ids) == false ){
            $arrMenuIds = self::getSystemMenuIdsByRole($ids);
            $map['id'] = $arrMenuIds;
        }
        
        $menuList = SystemMenu::withAttr('href', function($value, $data) {
                        return '/admin/' . $value;
                    })->withAttr('icon',function($value, $data){
                        return 'layui-icon ' . $value;
                    })
                    ->where($map)
                    ->order('sort','DESC')
                    ->select();
        if( $menuList == null ){
            throw new \think\Exception('菜单服务对象获取菜单列表失败');
        }
        return $menuList->toArray();
    }

    /**
     * 获取当前菜单信息
     * @MethodAuthor: 聂哥
     * @Date: 2022-10-28 15:32:09
     */
    public static function getInfo()
    {
        $map = [];
        if (empty($id)) {
            $controller = strtolower(request()->controller());
            $action     = request()->action();
            $map['href'] = $controller.'/'.$action;
        } else {
            $map['id'] = (int)$id;
        }
        $map['status'] = 1;
        $rows = SystemMenu::where($map)->field('id,title,href')->find();
        return $rows;
    }

    /**
     * 重置菜单
     * @MethodAuthor: 聂哥
     * @Date: 2022-10-28 15:32:09
     */
    public static function reset()
    {
        $uid = session('admin.id');
        $key = sprintf("%s_%s_menulist",
            $uid,
            session('current_module_name')
        );
        Cache::rm($key);
        Session::delete("role_menu_{$uid}");
    }
}